import json

from django.core.exceptions import ValidationError
from django.http import HttpRequest, JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth.hashers import check_password
from django.views.decorators.csrf import csrf_exempt

from .forms import LoginForm, SysUser


# Create your views here.
from .models import Role


def login(req: HttpRequest):
    if req.method == 'POST':
        form = LoginForm(req.POST)
        if form.is_valid():
            pwd = form.cleaned_data.get('pwd') # 用户输入的
            pwd2 = form.instance_.password  # 查询出来的用户口令
            # print(pwd, pwd2)
            if check_password(pwd, pwd2):
                # 前后端不 分离时，
                req.session['login_user'] = form.instance_
                return redirect('/')
            form.add_error('pwd', ValidationError('口令不正确'))

        errors = json.loads(form.errors.as_json())  # errors.as_json()是字符串
    return render(req, 'login.html', locals())

def to_index(req):
    return render(req, 'home.html', locals())


@csrf_exempt
def role(request):
    # objects = [
    #     {'id': 1, 'name': '系统管理员', 'code': 'admin'},
    #     {'id': 2, 'name': '普通管理员', 'code': 'staff'},
    #     {'id': 3, 'name': '仓库管理员', 'code': 'ware'},
    # ]
    if request.method == 'DELETE':
        id = request.GET.get('id')
        Role.objects.get(pk=id).delete()
        return JsonResponse({'code': 0})

    if request.method == 'POST':
        id = request.POST.get('id', None)
        name = request.POST.get('name')
        code = request.POST.get('code')

        # 判断是添加还是修改
        if id:
            role = Role.objects.get(pk=id)
            role.name = name
            role.code = code
        else:
            role = Role(name=name,code=code)
        role.save()

    objects = Role.objects.all().values()
    return render(request, 'role/list.html', locals())
